﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ServisniList.Core;

namespace ServisniList
{
    public partial class OpisRadaNovi : Form
    {

        #region Properties

        public bool UspjesnoKreiranNovi { get; set; }

        #endregion

        #region Constructor

        public OpisRadaNovi()
        {
            InitializeComponent();
        }

        #endregion

        #region Event handlers

        private void OpisRadaNovi_Load(object sender, EventArgs e)
        {
            opisRadaBindingSource.DataSource = new Core.OpisRada();
            UspjesnoKreiranNovi = false;
        }

        private void btnSpremi_Click(object sender, EventArgs e)
        {
            if (Validacija())
            {
                Core.OpisRada noviOpis = (Core.OpisRada)opisRadaBindingSource.DataSource;
                using (DataModelDataContext context = new DataModelDataContext(ConfigurationManager.ConnectionStrings["ServisniListConnectionString"].ConnectionString))
                {
                    context.OpisRadas.InsertOnSubmit(noviOpis);
                    context.SubmitChanges();
                }
                UspjesnoKreiranNovi = true;
                this.Close();
            }
        }

        private void opisTextBox_TextChanged(object sender, EventArgs e)
        {
            errNotifikacijaValidacije.SetError((TextBox)sender, null);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.KeyCode == Keys.Escape)
                this.Close();
        }

        #endregion

        #region Methods

        private bool Validacija()
        {
            errNotifikacijaValidacije.Clear();

            if (string.IsNullOrEmpty(txtOpis.Text))
            {
                errNotifikacijaValidacije.SetError(txtOpis, "Opis je obavezan, molim Vas da ga unesete !");
                return false;
            }    

            ServisniList.Core.OpisRada opisrada = null;

            using (DataModelDataContext context = new DataModelDataContext(ConfigurationManager.ConnectionStrings["ServisniListConnectionString"].ConnectionString))
            {
                opisrada = (from d in context.OpisRadas
                                            where d.Opis == txtOpis.Text
                                            select d).FirstOrDefault();

            }

            if (opisrada != null)
            {
                errNotifikacijaValidacije.SetError(txtOpis, "Opis rada već postoji !");
                return false;
            }

            return true;
        }

        #endregion

    }
}
